package com.djq.hhc.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.djq.hhc.dto.UserInfoDto;
import com.djq.hhc.holder.UserHolder;
import com.djq.hhc.mapper.UserFollowMapper;
import com.djq.hhc.model.user.UserFollow;
import com.djq.hhc.result.Result;
import com.djq.hhc.service.UserFollowService;
import com.djq.hhc.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.djq.hhc.redis.RedisConstants.USER_FOLLOW_KEY;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: dadd7
 * @Date: 2023/03/16/上午 9:28
 * @Description:
 */

@Service
@Transactional
public class UserFollowServiceImpl extends ServiceImpl<UserFollowMapper, UserFollow> implements UserFollowService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private UserInfoService userInfoService;

    @Override
    @Transactional
    public Result follow(Long followUserId, Boolean isFollow) {
        // 1.获取登录用户
        Long userId = UserHolder.getUser().getId();
        if (userId == null) {
            return Result.fail().message("未登录");
        }
        String key = USER_FOLLOW_KEY + userId;
        if (!isFollow) {
            UserFollow userFollow = new UserFollow();
            userFollow.setUserId(userId);
            userFollow.setFollowUserId(followUserId);
            boolean save = save(userFollow);
            if (save) {
                stringRedisTemplate.opsForSet().add(key, followUserId.toString());
                return Result.ok().message("关注成功");
            }
            return Result.fail().message("诶呀关注失败，出错了/(ㄒoㄒ)/~~");
        } else {
            QueryWrapper<UserFollow> queryWrapper = new QueryWrapper<UserFollow>();
            queryWrapper.eq("user_id", userId)
                    .eq("follow_user_id", followUserId);
            boolean remove = remove(queryWrapper);
            if (remove) {
                stringRedisTemplate.opsForSet().remove(key, followUserId.toString());
                return Result.ok().message("取关成功");
            }
            return Result.fail().message("诶呀取关失败，出错了/(ㄒoㄒ)/~~");
        }
    }

    @Override
    public Result isFollow(Long followUserId) {
        // 1.获取登录用户
        UserInfoDto user = UserHolder.getUser();
        if (user == null) {
            return Result.fail().message("未登录");
        }
        Long userId = user.getId();
        // 2.查询是否关注 select count(*) from tb_follow where user_id = ? and follow_user_id = ?
        Integer count = query().eq("user_id", userId).eq("follow_user_id",
                followUserId).count();
        // 3.判断
        return Result.ok(count > 0);
    }

    @Override
    public Result getCommonsFollow(Long id) {
        // 1.获取当前用户
        Long userId = UserHolder.getUser().getId();
        //key
        String key = USER_FOLLOW_KEY + userId;
        String key2 = USER_FOLLOW_KEY + id;
        //2.求交集
        Set<String> intersect = stringRedisTemplate.opsForSet().intersect(key, key2);
        if (intersect == null || intersect.isEmpty()) {
        // 无交集
            return Result.ok(Collections.emptyList());
        }
        // 3.解析id集合
        List<Long> ids = intersect.stream().map(Long::valueOf).collect(Collectors.toList());
        // 4.查询用户
        List<UserInfoDto> users = userInfoService.listByIds(ids)
                .stream()
                .map(user -> BeanUtil.copyProperties(user, UserInfoDto.class))
                .collect(Collectors.toList());
        return Result.ok(users);
    }

    @Override
    public Long getFollowNum(Long id) {
        if (id == null) {
            return null;
        }
        Long count = Long.valueOf(query().eq("user_id", id).count());
        return count;
    }

    @Override
    public Long getFansNum(Long id) {
        if (id == null) {
            return null;
        }
        Long count = Long.valueOf(query().eq("follow_user_id", id).count());
        return count;
    }
}
